package net;

import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;

public class UDPServer {
    //从（自定）固定端口接收数据报
    private static final int PORT = 4096;

    //本地文件目录要展示的根路径 （用来干嘛的？
    private static final String BASE_PATH = "E:/";

    public static void main4(String[] args) throws IOException {

        DatagramSocket socket = new DatagramSocket(PORT);

        while (true) {
            byte[] bytes = new byte[1024];
            //packet包含数据（字节流bytes）、客户端ip、端口号
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);

            System.out.println("等待接收来自客户端的UDP数据报...");
            //receive有阻塞等待功能（在接收到packet数据前阻塞等待）
            socket.receive(packet);
            System.out.printf("客户端IP:%s%n",packet.getAddress().getHostAddress());
            System.out.printf("客户端端口号:%s%n",packet.getPort());

            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                if (b == '\3') {
                    //取出字符之前的内容
                    String request = new String(bytes, 0, i);
                    System.out.printf("客户端请求的文件列表路径为:%s%n",BASE_PATH + request);

                    File dir = new File(BASE_PATH, request);
                    File[] children = dir.listFiles();

                    StringBuilder response = new StringBuilder();
                    if (children != null) {
                        for (File child: children) {
                            response.append(child.getName() + "\n");
                        }
                    }
                    //相应结束也按照约定的结束符1
                    response.append("/3");

                    byte[] responseData =
                            response.toString().getBytes(StandardCharsets.UTF_8);
                    //构造返回相应的数据报DatagramPacket，接收端（客户端）的数据报包含IP和端口号也要设置到相应的数据报中
                    DatagramPacket responsePacket =
                            new DatagramPacket(responseData, responseData.length, packet.getSocketAddress());
                    socket.send(responsePacket);
                    break;

                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //创建服务器端数据报，指定端口，可用于receive和sendUDP数据报
        DatagramSocket socket = new DatagramSocket(PORT);
        //不停地接收客户端UDP数据报
        while (true) {
            byte[] bytes = new byte[2048];
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            System.out.println("等待接收UDP数据报..");
            //从固定端口中
            socket.receive(packet);
            //getHostAddress获取IP地址
            System.out.printf("客户端IP:%s%n",packet.getAddress().getHostAddress());

            System.out.printf("客户端端口号:%s%n",packet.getPort());

            System.out.printf("客户端发送的原生数据为:%s%n",packet.getData());

            System.out.printf("客户端发送的文本数据为:%s%n",new String(packet.getData()));
        }
    }

}
